package servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import entities.Customer;

import service.customer.CustomerService;
import service.customer.CustomerServiceFactory;

/**
 * Servlet implementation class HonorRollServlet
 */
public class LoginServlet extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() 
    {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		HttpSession session = request.getSession();
		String username = request.getParameter("username");
		Customer customer = null;
		String addr = null;
		
		// Get the factory to create services. This is obtained from the web.xml configuration file
		// from parameter ServiceFactoryType
		CustomerServiceFactory factory = CustomerServiceFactory.getFactory(ServletInitParams.getServiceFactoryType(this));
		// Get an instance of the student service, as given by the factory
		CustomerService service = factory.getInstance();
		
		// Find the customer
		customer = service.findCustomer(username);
		/*if (customer == null){
			addr = "./html/customerNotFound.jsp";
		}*/
		try{
		if(customer.getPass().equals(request.getParameter("password"))) {
			session.setAttribute(customer.getName(), customer);
			addr = "./index.jsp";
		}
		else{
			addr = "./html/incorrectPassword.jsp";
		}
		}
		catch(NullPointerException e)
		{
			addr = "./html/customerNotFound.jsp";
		}
		if(username.equals("admin"))
			addr = "./html/admin.jsp";
		
		RequestDispatcher dispatcher = request.getRequestDispatcher(addr);
		dispatcher.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
